import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import pandas as pd
from tkinter.scrolledtext import ScrolledText
from datetime import datetime
from loguru import logger


# 场景人群分类选项（示例数据）
scene_options = [
    "价敏囤货人群", "奢美人群", "熬夜人群", "尝新人群", "潮流户外人群", "精致中产", "精致妈妈",
    "母婴行业意向", "换季人群", "追剧兴趣人群", "瘦身人群", "聚会出游人群", "都市白领", "养生人群",
    "学生党", "潮流女生", "质感女士", "奢侈品腕表兴趣人群", "自在户外【生活方式人群】",
    "自由畅行【生活方式人群】", "运动焕活【生活方式人群】", "孕育学习【生活方式人群】",
    "娱乐放松【生活方式人群】", "悦享奢华【生活方式人群】", "养身韧体【生活方式人群】",
    "虚拟人生【生活方式人群】", "美力加成【生活方式人群】", "心灵奇旅【生活方式人群】",
    "文艺沉浸【生活方式人群】", "数智未来【生活方式人群】", "舌尖盛宴【生活方式人群】",
    "浪漫囍事【生活方式人群】", "看世界【生活方式人群】", "家有萌宠【生活方式人群】",
    "发现附近【生活方式人群】", "成长进阶【生活方式人群】", "时尚态度【生活方式人群】",
    "家生活【生活方式人群】", "游牧青年【家生活特色人群】", "筑巢青年【家生活特色人群】",
    "全能生活家【家生活特色人群】", "居家策展人【家生活特色人群】", "踏青出游人群",
    "美养佳人【美力加成人群】", "风格日抛党【美力加成人群】", "精养奢美族【美力加成人群】",
    "变美练习生【美力加成人群】", "气场精英【美力加成人群】", "美研尖子生【美力加成人群】",
    "养宠人群", "养猫人群", "养狗人群"
]

# 节促人群分类选项（示例数据）
festival_options = [
    "618大促人群", "520送礼人群", "母亲节送礼人群", "七夕送礼人群", "中秋送礼人群", "国庆出游人群", "双十一购物人群"
]

# 策略人群行业数据
industry_data = {
    "美妆个护": ["国风美学家", "彩妆追新人", "科技先锋派", "养肤尝新族", "悦己美容家", "妆点练习生", "精致生活家","疗愈尝鲜党", "美肌理科生", "国货情怀党", "艺术玩妆派"],
    "食品饮料": ["美食研究僧", "美食早鸟侠", "质感美食家", "美食情怀党", "鱼和熊掌党", "不独美食家", "美食大玩家"],
    "游戏": ["射击游戏", "生存沙盒游戏", "二次元游戏", "女性向游戏", "主机游戏", "休闲经营游戏", "MOBA游戏", "角色扮演游戏", "策略游戏"],
    "宠物": ["携宠旅行家", "精养新中产", "为宠尝鲜派", "新晋铲屎官", "猫狗大赢家", "科学养宠人", "萌宠囤货人", "潮人养宠式", "娃宠两双全", "二次元养宠", "专属宠物角", "养生式养宠", "宠饭手艺人", "熟龄养宠人","校园养宠党", "陪嫁哈基米"],
    "母婴": ["新手妈妈", "新手爸爸", "富养妈妈", "小镇妈妈", "成分妈妈", "敏宝妈妈", "潮流妈妈", "chill妈妈"]
}

# 示例垂类人群选项
vertical_options = [
    "数码爱好者", "运动健身人群", "旅游达人",
    "汽车爱好者", "家居装修人群", "宠物主人"
]


class XiaohongshuAdTool:
    def __init__(self, root):
        self.root = root
        self.root.title("小红书广告计划创建工具")
        self.root.geometry("1500x800")

        self.main_canvas = tk.Canvas(root, borderwidth=0)
        self.scrollbar = ttk.Scrollbar(root, orient="vertical", command=self.main_canvas.yview)
        self.scrollable_frame = ttk.Frame(self.main_canvas)

        self.scrollable_frame.bind(
            "<Configure>",
            lambda e: self.main_canvas.configure(
                scrollregion=self.main_canvas.bbox("all")
            )
        )

        self.main_canvas.create_window((0, 0), window=self.scrollable_frame, anchor="nw")
        self.main_canvas.configure(yscrollcommand=self.scrollbar.set)

        # 使用 Grid 布局管理器
        root.grid_rowconfigure(0, weight=1)
        root.grid_columnconfigure(0, weight=19)  # 主界面占据95%
        root.grid_columnconfigure(1, weight=1)  # 滚动条占据5%

        self.main_canvas.grid(row=0, column=0, sticky="nsew")
        self.scrollbar.grid(row=0, column=1, sticky="ns")

        # 路径选项
        self.path_options = [
            "自点", "手点1", "手点2", "自互", "互互", "互点",
            "站外", "站外-cpc", "自动-CPI", "种草-CPI", "自动-CPTI", "种草-CPTI"
        ]

        # 定向类型选项
        self.target_options = ["通投", "智能定向", "高级定向"]

        # 性别选项
        self.gender_options = ["不限", "男", "女"]

        # 地域选项
        self.area_options = ["不限", "中国"]

        # 年龄选项
        self.age_options = ["不限", "18-22", "23-27", "28-32", "33-40", "41-50", ">50"]

        # 平台选项
        self.platform_options = ["不限", "Android", "iOS"]

        # 手机价格选项
        self.tel_price_options = [
            "不限", "1999元以下", "2000-3999元",
            "4000-5999元", "6000-7999元", "8000元+"
        ]

        # 转化组件
        self.trans_comp_options = ["无", "落地页组件", "私信组件", "门店组件", "搜索组件"]

        self.create_widgets()

    def create_widgets(self):
        # 主框架 - 设置更大的最小宽度
        main_frame = ttk.Frame(self.scrollable_frame, padding="10")
        main_frame.pack(fill=tk.BOTH, expand=True)
        main_frame.columnconfigure(0, weight=1)

        # 广告计划信息部分 - 设置更大的宽度
        plan_frame = ttk.LabelFrame(main_frame, text="广告计划信息", padding="10")
        plan_frame.pack(fill=tk.X, pady=5, padx=5)

        # 账号名称
        ttk.Label(plan_frame, text="账号名称:").grid(row=0, column=0, sticky=tk.W, pady=2)
        self.account_name = ttk.Entry(plan_frame, width=50)  # 增加宽度
        self.account_name.grid(row=0, column=1, columnspan=3, sticky=tk.EW, pady=2, padx=5)  # 添加padx
        self.account_name.insert(0, "账号名称")
        plan_frame.columnconfigure(1, weight=1)  # 使输入框可扩展

        # 账号ID
        ttk.Label(plan_frame, text="账号ID:").grid(row=1, column=0, sticky=tk.W, pady=2)
        self.account_id = ttk.Entry(plan_frame, width=50)
        self.account_id.grid(row=1, column=1, columnspan=3, sticky=tk.EW, pady=2, padx=5)
        self.account_id.insert(0, "账号ID")

        # 路径名称
        ttk.Label(plan_frame, text="路径名称:").grid(row=2, column=0, sticky=tk.W, pady=2)
        self.path_name = tk.StringVar(value=self.path_options[0])

        # 使用Frame来组织路径选择按钮 - 增加宽度
        path_frame = ttk.Frame(plan_frame)
        path_frame.grid(row=2, column=1, columnspan=6, sticky=tk.EW, pady=2, padx=5)

        # 每行显示4个选项 - 增加按钮间距
        for i, option in enumerate(self.path_options):
            row = i // 6
            col = i % 6
            rb = ttk.Radiobutton(
                path_frame,
                text=option,
                variable=self.path_name,
                value=option
            )
            rb.grid(row=row, column=col, sticky=tk.W, padx=10, pady=5)  # 增加padx

        # 指定预算
        ttk.Label(plan_frame, text="指定预算:").grid(row=3, column=0, sticky=tk.W, pady=2)
        self.plan_budget = ttk.Entry(plan_frame, width=80)  # 增加宽度
        self.plan_budget.grid(row=3, column=1, sticky=tk.W, pady=2, padx=5)
        self.plan_budget.insert(0, "100.0")
        ttk.Label(plan_frame, text="元").grid(row=3, column=2, sticky=tk.EW, pady=2)

        # 消耗速率单选框组
        ttk.Label(plan_frame, text="消耗速率:").grid(row=4, column=0, sticky=tk.W, pady=2)
        self.consume_rate_text = tk.StringVar(value="均匀消耗")
        # 创建一个子 Frame 来存放 Radiobutton
        radio_frame = ttk.Frame(plan_frame)
        radio_frame.grid(row=4, column=1, sticky=tk.W)  # 放在第 4 行第 1 列

        # 使用 pack() 水平排列 Radiobutton
        for option in ["加速消耗", "均匀消耗"]:
            rb = ttk.Radiobutton(
                radio_frame,
                text=option,
                variable=self.consume_rate_text,
                value=option
            )
            rb.pack(side=tk.LEFT, padx=2)  # side=LEFT 让它们水平排列，padx=2 调整间距

        # 笔记ID
        ttk.Label(plan_frame, text="笔记ID:").grid(row=5, column=0, sticky=tk.W, pady=2)
        self.unit_id = ttk.Entry(plan_frame, width=50)
        self.unit_id.grid(row=5, column=1, columnspan=3, sticky=tk.EW, pady=2, padx=5)
        self.unit_id.insert(0, "askdsfhjdhfjd")

        # # 人群定向包
        # ttk.Label(plan_frame, text="人群定向包:").grid(row=6, column=0, sticky=tk.W, pady=2)
        # self.crowd_pack_text = ttk.Entry(plan_frame, width=50)
        # self.crowd_pack_text.grid(row=6, column=1, columnspan=3, sticky=tk.EW, pady=2, padx=5)
        # self.crowd_pack_text.insert(0, "痛点场景人群")

        # 分隔线
        ttk.Separator(main_frame, orient=tk.HORIZONTAL).pack(fill=tk.X, pady=10)

        # 定向部分 - 设置更大的宽度
        target_frame = ttk.LabelFrame(main_frame, text="定向", padding="10")
        target_frame.pack(fill=tk.BOTH, expand=True, padx=5)  # 改为fill=tk.BOTH

        # 定向类型
        target_type_out_frame = ttk.Frame(target_frame)
        target_type_out_frame.grid(row=0, column=0, sticky=tk.W, columnspan=6)  # 放在第 4 行第 1 列

        ttk.Label(target_type_out_frame, text="定向类型:").grid(row=0, column=0, sticky=tk.W, pady=2)
        self.target_type = tk.StringVar(value=self.target_options[0])
        for i, option in enumerate(self.target_options):
            rb = ttk.Radiobutton(
                target_type_out_frame,
                text=option,
                variable=self.target_type,
                value=option,
                command=self.update_advanced_targeting
            )
            rb.grid(row=0, column=i + 1, sticky=tk.W, padx=10, pady=5)  # 增加padx


        # 人群定向包
        # 创建一个子 Frame 来存放 Radiobutton
        pack_frame = ttk.Frame(target_frame)
        pack_frame.grid(row=1, column=0, sticky=tk.W, columnspan=6)  # 放在第 4 行第 1 列

        self.crowd_pack_frame_label = ttk.Label(pack_frame, text="人群定向包:")
        self.crowd_pack_frame_label.grid(row=0, column=0, sticky=tk.W, pady=2)
        self.crowd_pack_text = ScrolledText(pack_frame, width=50, height=8)
        self.crowd_pack_text.grid(row=0, column=1, columnspan=3, sticky=tk.EW, pady=2, padx=5)

        self.crowd_pack_frame_label.grid_remove()
        self.crowd_pack_text.grid_remove()


        # 高级定向选项卡 - 设置更大的尺寸
        self.advanced_targeting_notebook = ttk.Notebook(target_frame)
        self.advanced_targeting_notebook.grid(row=2, column=0, columnspan=6, sticky=tk.NSEW, pady=10, padx=5)
        target_frame.rowconfigure(1, weight=1)  # 使notebook可垂直扩展
        target_frame.columnconfigure(0, weight=1)  # 使notebook可水平扩展

        # 平台精选标签页 - 设置更大的尺寸
        self.platform_selected_tab = ttk.Frame(self.advanced_targeting_notebook)
        self.platform_selected_tab.pack(fill=tk.BOTH, expand=True)


        # 是否拆分平台精选包
        split_frame = ttk.LabelFrame(self.platform_selected_tab, text="拆分定向包:")
        split_frame.pack(pady=10)

        # 添加提示信息
        ttk.Label(
            split_frame,
            text="选择是否将多个定向包拆分为一组独立选项(每组敲两个回车分隔), 否:对应所选的全部定向包, 是:对应所选的全部定向包按两个回车符拆分之后的其中一组选项",
            font=("Arial", 9),  # 设置字体大小
            foreground="gray"  # 设置文字颜色为灰色
        ).pack(anchor=tk.W, pady=(0, 5))  # 放置在顶部，与下方控件保持间距


        # 使用IntVar更方便布尔判断
        self.split_pingtaijingxuan_var = tk.IntVar(value=0)  # 0=否，1=是

        # 单选按钮
        ttk.Radiobutton(
            split_frame,
            text="否",
            variable=self.split_pingtaijingxuan_var,
            value=0
        ).pack(side=tk.LEFT, padx=10)

        ttk.Radiobutton(
            split_frame,
            text="是",
            variable=self.split_pingtaijingxuan_var,
            value=1
        ).pack(side=tk.LEFT, padx=10)





        # 创建左右两个框架 - 设置更大的尺寸
        left_frame = ttk.LabelFrame(self.platform_selected_tab, text="场景人群分类", padding=15)  # 增加padding
        right_frame = ttk.LabelFrame(self.platform_selected_tab, text="节促人群分类", padding=15)
        left_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=10, pady=10)  # 增加padx/pady
        right_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True, padx=10, pady=10)

        # 存储选项变量的字典
        self.scene_vars = {}  # 场景人群选项变量
        self.festival_vars = {}  # 节促人群选项变量

        # 添加场景人群分类多选框 - 横向三列布局
        ttk.Label(left_frame, text="请选择场景人群:", font=('Arial', 10, 'bold')).grid(row=0, column=0, columnspan=3,sticky=tk.W, pady=5)

        # 计算每列应该有多少个选项
        num_columns = 4
        options_per_column = (len(scene_options) + num_columns - 1) // num_columns

        for i, option in enumerate(scene_options):
            var = tk.IntVar(value=0)
            self.scene_vars[option] = var

            # 计算当前选项应该放在哪一行哪一列
            row = i % options_per_column + 1  # +1 因为第0行是标题
            column = i // options_per_column

            cb = ttk.Checkbutton(
                left_frame,
                text=option,
                variable=var,
                padding=(5, 5)
            )
            cb.grid(row=row, column=column, sticky=tk.W, padx=10, pady=5)

        # 添加节促人群分类多选框 - 增加间距
        ttk.Label(right_frame, text="请选择节促人群:", font=('Arial', 10, 'bold')).pack(anchor=tk.W, pady=5)
        for option in festival_options:
            var = tk.IntVar(value=0)
            self.festival_vars[option] = var
            cb = ttk.Checkbutton(
                right_frame,
                text=option,
                variable=var,
                padding=(5, 5)
            )
            cb.pack(anchor=tk.W, padx=10, pady=5)

        self.advanced_targeting_notebook.add(self.platform_selected_tab, text="平台精选")

        '''行业人群标签页'''
        self.industry_audience_tab = ttk.Frame(self.advanced_targeting_notebook)
        self.advanced_targeting_notebook.add(self.industry_audience_tab, text="行业人群")

        # 主框架
        main_industry_frame = ttk.Frame(self.industry_audience_tab)
        main_industry_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)


        # 是否拆分行业人群
        split_hangyerenqun_frame = ttk.LabelFrame(main_industry_frame, text="拆分定向包:")
        split_hangyerenqun_frame.pack(pady=10)

        # 添加提示信息
        ttk.Label(
            split_hangyerenqun_frame,
            text="选择是否将多个定向包拆分为一组独立选项(每组敲两个回车分隔), 否:对应所选的全部定向包, 是:对应所选的全部定向包按两个回车符拆分之后的其中一组选项",
            font=("Arial", 9),  # 设置字体大小
            foreground="gray"  # 设置文字颜色为灰色
        ).pack(anchor=tk.W, pady=(0, 5))  # 放置在顶部，与下方控件保持间距


        # 使用IntVar更方便布尔判断
        self.split_hangyerenqun_var = tk.IntVar(value=0)  # 0=否，1=是

        # 单选按钮
        ttk.Radiobutton(
            split_hangyerenqun_frame,
            text="否",
            variable=self.split_hangyerenqun_var,
            value=0
        ).pack(side=tk.LEFT, padx=10)

        ttk.Radiobutton(
            split_hangyerenqun_frame,
            text="是",
            variable=self.split_hangyerenqun_var,
            value=1
        ).pack(side=tk.LEFT, padx=10)

        # 策略人群分类
        strategy_frame = ttk.LabelFrame(main_industry_frame, text="策略人群", padding=10)
        strategy_frame.pack(fill=tk.BOTH, expand=True, pady=5)

        # 垂类人群分类
        vertical_frame = ttk.LabelFrame(main_industry_frame, text="垂类人群", padding=10)
        vertical_frame.pack(fill=tk.BOTH, expand=True, pady=5)

        # 策略人群内部框架
        strategy_inner_frame = ttk.Frame(strategy_frame)
        strategy_inner_frame.pack(fill=tk.BOTH, expand=True)

        # 策略人群一级行业框架 (左侧)
        primary_industry_frame = ttk.LabelFrame(strategy_inner_frame, text="一级行业", padding=10)
        primary_industry_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=5)
        self.celue_left_text = ScrolledText(primary_industry_frame, width=60, height=20)
        self.celue_left_text.pack(padx=5, pady=10)


        # 策略人群人群包框架 (右侧)
        self.audience_pack_frame = ttk.LabelFrame(strategy_inner_frame, text="人群包", padding=10)
        self.audience_pack_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True, padx=5)
        self.celue_right_text = ScrolledText(self.audience_pack_frame, width=60, height=20)
        self.celue_right_text.pack(padx=5, pady=10)

        # 垂类人群内部框架
        chuilei_inner_frame = ttk.Frame(vertical_frame)
        chuilei_inner_frame.pack(fill=tk.BOTH, expand=True)

        # 垂类人群一级行业框架 (左侧)
        chuilei_primary_industry_frame = ttk.LabelFrame(chuilei_inner_frame, text="一级行业", padding=10)
        chuilei_primary_industry_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=5)
        self.chuilei_left_text = ScrolledText(chuilei_primary_industry_frame, width=60, height=20)
        self.chuilei_left_text.pack(padx=5, pady=10)

        # 垂类人群包框架 (右侧)
        self.chuilei_audience_pack_frame = ttk.LabelFrame(chuilei_inner_frame, text="人群包", padding=10)
        self.chuilei_audience_pack_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True, padx=5)
        self.chuilei_right_text = ScrolledText(self.chuilei_audience_pack_frame, width=60, height=20)
        self.chuilei_right_text.pack(padx=5, pady=10)





        '''行业兴趣标签页'''
        self.industry_interest_tab = ttk.Frame(self.advanced_targeting_notebook)
        self.advanced_targeting_notebook.add(self.industry_interest_tab, text="行业兴趣")

        # 行业兴趣主框架
        main_interest_frame = ttk.Frame(self.industry_interest_tab)
        main_interest_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)




        # 是否拆分行业人群
        split_hangyexingqu_frame = ttk.LabelFrame(main_interest_frame, text="拆分定向包:")
        split_hangyexingqu_frame.pack(pady=10)


        # 添加提示信息
        ttk.Label(
            split_hangyexingqu_frame,
            text="选择是否将多个定向包拆分为一组独立选项(每组敲两个回车分隔), 否:对应所选的全部定向包, 是:对应所选的全部定向包按两个回车符拆分之后的其中一组选项",
            font=("Arial", 9),  # 设置字体大小
            foreground="gray"  # 设置文字颜色为灰色
        ).pack(anchor=tk.W, pady=(0, 5))  # 放置在顶部，与下方控件保持间距

        # 使用IntVar更方便布尔判断
        self.split_hangyexingqu_var = tk.IntVar(value=0)  # 0=否，1=是

        # 单选按钮
        ttk.Radiobutton(
            split_hangyexingqu_frame,
            text="否",
            variable=self.split_hangyexingqu_var,
            value=0
        ).pack(side=tk.LEFT, padx=10)

        ttk.Radiobutton(
            split_hangyexingqu_frame,
            text="是",
            variable=self.split_hangyexingqu_var,
            value=1
        ).pack(side=tk.LEFT, padx=10)







        # 行业阅读兴趣分类
        read_interest_group = ttk.LabelFrame(main_interest_frame, text="行业阅读兴趣", padding=10)
        read_interest_group.pack(fill=tk.BOTH, expand=True, pady=5)

        # 行业购物兴趣分类
        shoppint_interest_group = ttk.LabelFrame(main_interest_frame, text="行业购物兴趣", padding=10)
        shoppint_interest_group.pack(fill=tk.BOTH, expand=True, pady=5)

        # 行业阅读兴趣内部框架
        read_interest_frame = ttk.Frame(read_interest_group)
        read_interest_frame.pack(fill=tk.BOTH, expand=True)

        # 行业阅读兴趣一级行业框架 (左侧)
        primary_read_interest_frame_frame = ttk.LabelFrame(read_interest_frame, text="一级行业", padding=10)
        primary_read_interest_frame_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=5)
        self.yuedu_left_text = ScrolledText(primary_read_interest_frame_frame, width=60, height=20)
        self.yuedu_left_text.pack(padx=5, pady=10)

        # 行业阅读兴趣人群包框架 (右侧)
        self.primary_audience_pack_frame = ttk.LabelFrame(read_interest_frame, text="人群包", padding=10)
        self.primary_audience_pack_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True, padx=5)
        self.yuedu_right_text = ScrolledText(self.primary_audience_pack_frame, width=60, height=20)
        self.yuedu_right_text.pack(padx=5, pady=10)

        self.yuedu_right_text.config(state="disabled", background="#d3d3d3")
        # 行业购物兴趣内部框架
        shopping_inner_frame = ttk.Frame(shoppint_interest_group)
        shopping_inner_frame.pack(fill=tk.BOTH, expand=True)

        # 行业购物兴趣一级行业框架 (左侧)
        shopping_primary_industry_frame = ttk.LabelFrame(shopping_inner_frame, text="一级行业", padding=10)
        shopping_primary_industry_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=5)
        self.shopping_left_text = ScrolledText(shopping_primary_industry_frame, width=60, height=20)
        self.shopping_left_text.pack(padx=5, pady=10)

        # 行业购物兴趣人群包框架 (右侧)
        self.shopping_chuilei_audience_pack_frame = ttk.LabelFrame(shopping_inner_frame, text="人群包", padding=10)
        self.shopping_chuilei_audience_pack_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True, padx=5)
        self.shopping_right_text = ScrolledText(self.shopping_chuilei_audience_pack_frame, width=60, height=20)
        self.shopping_right_text.pack(padx=5, pady=10)









        '''关键词标签页'''
        self.keyword_tab = ttk.Frame(self.advanced_targeting_notebook)
        self.advanced_targeting_notebook.add(self.keyword_tab, text="关键词")

        # 是否拆分行业人群
        split_guanjianci_frame = ttk.LabelFrame(self.keyword_tab, text="拆分定向包:")
        split_guanjianci_frame.pack(pady=10)

        # 添加提示信息
        ttk.Label(
            split_guanjianci_frame,
            text="选择是否将多个定向包拆分为一组独立选项(每组敲两个回车分隔), 否:对应所选的全部定向包, 是:对应所选的全部定向包按两个回车符拆分之后的其中一组选项",
            font=("Arial", 9),  # 设置字体大小
            foreground="gray"  # 设置文字颜色为灰色
        ).pack(anchor=tk.W, pady=(0, 5))  # 放置在顶部，与下方控件保持间距

        # 使用IntVar更方便布尔判断
        self.split_guanjianci_var = tk.IntVar(value=0)  # 0=否，1=是

        # 单选按钮
        ttk.Radiobutton(
            split_guanjianci_frame,
            text="否",
            variable=self.split_guanjianci_var,
            value=0
        ).pack(side=tk.LEFT, padx=10)

        ttk.Radiobutton(
            split_guanjianci_frame,
            text="是",
            variable=self.split_guanjianci_var,
            value=1
        ).pack(side=tk.LEFT, padx=10)


        # 创建关键词兴趣部分
        keyword_interest_frame = ttk.LabelFrame(self.keyword_tab, text="关键词兴趣", padding=10)
        keyword_interest_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=5, pady=5)

        # 关键词兴趣文本框
        self.keyword_interest_text = ScrolledText(keyword_interest_frame, width=60, height=20)
        self.keyword_interest_text.pack(padx=5, pady=5)

        # 创建关键词行为部分
        keyword_behavior_frame = ttk.LabelFrame(self.keyword_tab, text="关键词行为", padding=10)
        keyword_behavior_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True, padx=5, pady=5)

        # 时间范围选项
        time_range_frame = ttk.Frame(keyword_behavior_frame)
        time_range_frame.pack(fill=tk.X, pady=5)

        ttk.Label(time_range_frame, text="时间范围:").pack(side=tk.LEFT, padx=5, pady=5)

        self.time_range_var = tk.StringVar(value="7")
        for option in ["3天内", "7天内", "15天内", "30天内"]:
            rb = ttk.Radiobutton(
                time_range_frame,
                text=option,
                variable=self.time_range_var,
                value=option.split("天")[0]
            )
            rb.pack(side=tk.LEFT, padx=5, pady=5)

        # 关键词内容选项
        keyword_content_frame = ttk.Frame(keyword_behavior_frame)
        keyword_content_frame.pack(fill=tk.X, pady=10)

        ttk.Label(keyword_content_frame, text="关键词内容:").pack(side=tk.LEFT, padx=5, pady=5)

        self.keyword_content_vars = {
            "搜索": tk.IntVar(value=1),
            "互动": tk.IntVar(value=0),
            "阅读": tk.IntVar(value=0)
        }

        for option, var in self.keyword_content_vars.items():
            cb = ttk.Checkbutton(
                keyword_content_frame,
                text=option,
                variable=var
            )
            cb.pack(side=tk.LEFT, padx=5, pady=5)

        # 关键词行为文本框
        self.keyword_behavior_text = ScrolledText(keyword_behavior_frame, width=60, height=10)
        self.keyword_behavior_text.pack(padx=5, pady=5)

        '''人群包搜索框标签页'''
        self.audience_package_tab = ttk.Frame(self.advanced_targeting_notebook)
        ttk.Label(self.audience_package_tab, text="输入人群包，每行一个").pack(pady=5)

        # 是否拆分行业人群
        split_renqunbao_frame = ttk.LabelFrame(self.audience_package_tab, text="拆分定向包:")
        split_renqunbao_frame.pack(pady=10)

        # 添加提示信息
        ttk.Label(
            split_renqunbao_frame,
            text="选择是否将多个定向包拆分为一组独立选项(每组敲两个回车分隔), 否:对应所选的全部定向包, 是:对应所选的全部定向包按两个回车符拆分之后的其中一组选项",
            font=("Arial", 9),  # 设置字体大小
            foreground="gray"  # 设置文字颜色为灰色
        ).pack(anchor=tk.W, pady=(0, 5))  # 放置在顶部，与下方控件保持间距

        # 使用IntVar更方便布尔判断
        self.split_renqunbao_var = tk.IntVar(value=0)  # 0=否，1=是

        # 单选按钮
        ttk.Radiobutton(
            split_renqunbao_frame,
            text="否",
            variable=self.split_renqunbao_var,
            value=0
        ).pack(side=tk.LEFT, padx=10)

        ttk.Radiobutton(
            split_renqunbao_frame,
            text="是",
            variable=self.split_renqunbao_var,
            value=1
        ).pack(side=tk.LEFT, padx=10)

        self.audience_package_text = ScrolledText(self.audience_package_tab, width=60, height=20)
        self.audience_package_text.pack(padx=5, pady=5)
        self.advanced_targeting_notebook.add(self.audience_package_tab, text="人群包")

        # 初始化高级定向选项卡为隐藏
        self.advanced_targeting_notebook.grid_remove()

        # 分隔线
        ttk.Separator(main_frame, orient=tk.HORIZONTAL).pack(fill=tk.X, pady=10)

        # 更多定向部分
        more_target_frame = ttk.LabelFrame(main_frame, text="更多定向", padding="10")
        more_target_frame.pack(fill=tk.X, pady=5)

        # 性别
        gender_out_frame = ttk.Frame(more_target_frame)
        gender_out_frame.grid(row=0, column=1, sticky=tk.W, columnspan=6)  # 放在第 4 行第 1 列

        ttk.Label(more_target_frame, text="性别:").grid(row=0, column=0, sticky=tk.W, pady=2)
        self.gender = tk.StringVar(value=self.gender_options[0])
        for i, option in enumerate(self.gender_options):
            rb = ttk.Radiobutton(
                gender_out_frame,
                text=option,
                variable=self.gender,
                value=option
            )
            rb.grid(row=0, column=i + 2, sticky=tk.W, padx=5, pady=2)

        # 地域
        ttk.Label(more_target_frame, text="地域:").grid(row=1, column=0, sticky=tk.W, pady=2)

        area_out_frame = ttk.Frame(more_target_frame)
        area_out_frame.grid(row=1, column=1, sticky=tk.W, columnspan=6)  # 放在第 4 行第 1 列

        self.area = tk.StringVar(value=self.area_options[1])
        for i, option in enumerate(self.area_options):
            rb = ttk.Radiobutton(
                area_out_frame,
                text=option,
                variable=self.area,
                value=option
            )
            rb.grid(row=1, column=i + 1, sticky=tk.W, padx=5, pady=2)

        # 年龄
        ttk.Label(more_target_frame, text="年龄:").grid(row=2, column=0, sticky=tk.W, pady=2)
        self.age_vars = []
        age_frame = ttk.Frame(more_target_frame)
        age_frame.grid(row=2, column=1, columnspan=6, sticky=tk.W)

        for i, option in enumerate(self.age_options):
            var = tk.IntVar(value=1 if option == "不限" else 0)
            cb = ttk.Checkbutton(
                age_frame,
                text=option,
                variable=var
            )
            cb.grid(row=0, column=i, sticky=tk.W, padx=5, pady=2)
            self.age_vars.append((option, var))

        # 平台
        platform_out_frame = ttk.Frame(more_target_frame)
        platform_out_frame.grid(row=3, column=1, sticky=tk.W, columnspan=6)  # 放在第 4 行第 1 列

        ttk.Label(more_target_frame, text="平台:").grid(row=3, column=0, sticky=tk.W, pady=2)
        self.platform = tk.StringVar(value=self.platform_options[0])
        for i, option in enumerate(self.platform_options):
            rb = ttk.Radiobutton(
                platform_out_frame,
                text=option,
                variable=self.platform,
                value=option
            )
            rb.grid(row=3, column=i + 1, sticky=tk.W, padx=5, pady=2)

        # 手机价格
        ttk.Label(more_target_frame, text="手机价格:").grid(row=4, column=0, sticky=tk.W, pady=2)
        self.tel_price_vars = []
        tel_price_frame = ttk.Frame(more_target_frame)
        tel_price_frame.grid(row=4, column=1, columnspan=6, sticky=tk.W)

        # 每行显示3个选项
        for i, option in enumerate(self.tel_price_options):
            var = tk.IntVar(value=1 if option == "不限" else 0)
            cb = ttk.Checkbutton(
                tel_price_frame,
                text=option,
                variable=var
            )
            cb.grid(row=4, column=i+1, sticky=tk.W, padx=5, pady=2)
            self.tel_price_vars.append((option, var))


        # 目标成本
        ttk.Label(more_target_frame, text="目标成本:").grid(row=5, column=0, sticky=tk.W, pady=2)
        self.target_cost_text = ttk.Entry(more_target_frame, width=50)
        self.target_cost_text.grid(row=5, column=1, columnspan=1, sticky=tk.W, pady=2, padx=2)
        self.target_cost_text.insert(0, "0.6")



        # 分隔线
        ttk.Separator(main_frame, orient=tk.HORIZONTAL).pack(fill=tk.X, pady=10)

        # 创意部分
        creative_frame = ttk.LabelFrame(main_frame, text="创意信息", padding="10")
        creative_frame.pack(fill=tk.X, pady=5)

        # 创意名称
        self.creative_lable_name = ttk.Label(creative_frame, text="创意名称:")
        self.creative_lable_name.grid(row=1, column=0, sticky=tk.W, pady=2)
        self.creative_name_text = ttk.Entry(creative_frame, width=50)
        self.creative_name_text.grid(row=1, column=1, columnspan=1, sticky=tk.W, pady=2, padx=2)

        # 监测链接
        ttk.Label(creative_frame, text="监测链接:").grid(row=2, column=0, sticky=tk.W, pady=2)
        self.monitor_text = ScrolledText(creative_frame, width=50, height=5)
        self.monitor_text.grid(row=2, column=1, columnspan=1, sticky=tk.W, pady=2, padx=2)

        # 行业资质
        ttk.Label(creative_frame, text="行业资质:").grid(row=3, column=0, sticky=tk.W, pady=2)
        self.indus_qualify_text = ttk.Entry(creative_frame, width=50)
        self.indus_qualify_text.grid(row=3, column=1, columnspan=1, sticky=tk.W, pady=2, padx=2)

        # 转化组件
        self.trans_comp_func(creative_frame)













        # 分隔线
        ttk.Separator(main_frame, orient=tk.HORIZONTAL).pack(fill=tk.X, pady=10)

        # 结尾部分（使用pack布局实现居中）
        end_frame = ttk.LabelFrame(main_frame, padding="10")
        end_frame.pack(fill=tk.X, pady=5)

        # 创建容器Frame用于居中
        center_frame = ttk.Frame(end_frame)
        center_frame.pack(expand=True)  # 关键：expand=True允许居中

        # 计划条数控件
        self.lable_plan_num = ttk.Label(center_frame, text="生成计划条数(填写数字):")
        self.lable_plan_num.pack(side=tk.LEFT, pady=2)

        self.plan_num_text = ttk.Entry(center_frame, width=20)
        self.plan_num_text.insert(0, "1")
        self.plan_num_text.pack(side=tk.LEFT, pady=2, padx=2)


        # 提交按钮
        submit_btn = ttk.Button(
            main_frame,
            text="生成Excel",
            command=self.generate_excel
        )
        submit_btn.pack(pady=20)

    def trans_comp_func(self, creative_frame):
        # 转化组件
        ttk.Label(creative_frame, text="转化组件:").grid(row=4, column=0, sticky=tk.W, pady=2)

        # 创建一个中间容器Frame来包裹单选按钮
        trans_comp_frame = ttk.Frame(creative_frame)
        trans_comp_frame.grid(row=4, column=1, columnspan=len(self.trans_comp_options), sticky=tk.W)
        self.trans_comp_type = tk.StringVar(value=self.trans_comp_options[0])
        for i, option in enumerate(self.trans_comp_options):
            rb = ttk.Radiobutton(
                trans_comp_frame,
                text=option,
                variable=self.trans_comp_type,
                value=option,
                command=self.update_trans_comp
            )
            rb.pack(side=tk.LEFT, padx=10)  # 使用pack布局并排排列


        # 组件位置
        self.comp_location_lable = ttk.Label(creative_frame, text="组件位置:")
        self.comp_location_lable.grid(row=5, column=0, sticky=tk.NW, pady=2)  # 使用sticky=tk.NW对齐顶部


        # 第一行：图片或视频底部
        self.image_video_bottom_frame = ttk.Frame(creative_frame)
        self.image_video_bottom_frame.grid(row=5, column=1, sticky=tk.W)

        self.bottom_var = tk.IntVar(value=1)  # 默认选中
        self.bottom_cb = ttk.Checkbutton(
            self.image_video_bottom_frame,
            text="图片或视频底部",
            variable=self.bottom_var,
            command=lambda: self.toggle_textbox(self.bottom_var, self.bottom_entry)
        )
        self.bottom_cb.grid(row=5, column=1, sticky=tk.W, padx=10, pady=2)
        self.bottom_entry = ttk.Entry(self.image_video_bottom_frame, width=60)
        self.bottom_entry.grid(row=5, column=2, sticky=tk.W, padx=5, pady=2)
        self.bottom_entry.insert(0, "搜索词")  # 设置默认值


        # 第二行：置顶评论
        self.top_comment_frame = ttk.Frame(creative_frame)
        self.top_comment_frame.grid(row=6, column=1, sticky=tk.W)

        self.comment_var = tk.IntVar(value=0)  # 默认不选中
        self.comment_cb = ttk.Checkbutton(
            self.top_comment_frame,
            text="置顶评论         ",
            variable=self.comment_var,
            command=lambda: self.toggle_textbox(self.comment_var, self.comment_entry)
        )
        self.comment_cb.grid(row=6, column=1, sticky=tk.W, padx=10, pady=2)
        self.comment_entry = ttk.Entry(self.top_comment_frame, width=60)
        self.comment_entry.grid(row=6, column=2, sticky=tk.E, padx=5, pady=2)
        self.comment_entry.insert(0, "默认评论文案")

        self.comp_location_lable.grid_remove()
        self.image_video_bottom_frame.grid_remove()
        self.top_comment_frame.grid_remove()


    def toggle_textbox(self, var, entry):
        if var.get():  # 如果选中
            print(f"文本框的值:{entry.get()}")
            entry.grid()  # 显示文本框
        else:
            entry.grid_remove()  # 隐藏文本框

    def update_trans_comp(self):
        if self.trans_comp_type.get() == "搜索组件":
            self.bottom_var.set(1)
            self.comment_var.set(1)

            self.comp_location_lable.grid()
            self.image_video_bottom_frame.grid()
            self.top_comment_frame.grid()
        else:
            self.bottom_var.set(0)
            self.comment_var.set(0)

            self.comp_location_lable.grid_remove()
            self.image_video_bottom_frame.grid_remove()
            self.top_comment_frame.grid_remove()
            print(f"转化组件:{self.trans_comp_type.get()}")

    def get_selected_scenes(self):
        """获取选中的场景人群分类"""
        return [option for option, var in self.scene_vars.items() if var.get() == 1]

    def get_selected_festivals(self):
        """获取选中的节促人群分类"""
        return [option for option, var in self.festival_vars.items() if var.get() == 1]

    def update_advanced_targeting(self):
        """根据选择的定向类型显示或隐藏高级定向选项卡"""
        if self.target_type.get() == "高级定向":
            self.crowd_pack_frame_label.grid()
            self.crowd_pack_text.grid()
            self.advanced_targeting_notebook.grid()
        else:
            self.crowd_pack_frame_label.grid_remove()
            self.crowd_pack_text.grid_remove()
            self.advanced_targeting_notebook.grid_remove()


    def get_selected_ages(self):
        """获取选中的年龄范围"""
        selected = [option for option, var in self.age_vars if var.get() == 1]
        if "不限" in selected or not selected:
            return "不限"
        return "\n".join(selected)

    def get_selected_tel_prices(self):
        """获取选中的手机价格范围"""
        selected = [option for option, var in self.tel_price_vars if var.get() == 1]
        if "不限" in selected or not selected:
            return "不限"
        return "\n".join(selected)

    def validate_inputs(self):
        """验证输入数据"""
        errors = []

        # 检查创意名称
        if not self.creative_name_text.get().strip():
            self.creative_lable_name.config(foreground='red')
            errors.append("创意名称不能为空")

        # 检查账号名称
        if not self.account_name.get().strip():
            errors.append("账号名称不能为空")

        # 检查账号ID
        if not self.account_id.get().strip():
            errors.append("账号ID不能为空")

        # 检查预算是否为有效数字
        try:
            budget = float(self.plan_budget.get())
            if budget <= 0:
                errors.append("预算必须大于0")
        except ValueError:
            errors.append("预算必须是有效的数字")

        # 检查笔记ID
        if not self.unit_id.get().strip():
            errors.append("笔记ID不能为空")
        # 如果是高级定向，人群定向包不能为空
        if self.target_type.get() == "高级定向":
            if not self.crowd_pack_text.get("1.0", tk.END).strip():
                errors.append("选择高级定向时，人群定向包不能为空")
        return errors

    def map_target_type(self):
        target_text = self.target_type.get()
        if "高级定向" == target_text:
            return self.crowd_pack_text.get("1.0", tk.END).strip()
        else:
            return target_text
    # 生成计划名
    def generate_plan_name(self):
        formatted_today_date = datetime.now().strftime("%m%d") # 当天日期
        path_name = self.path_name.get() # 路径名称
        crowd_pack_name = self.map_target_type() # 人群定向包
        creative_name = self.creative_name_text.get().strip() # 创意名称
        return f"{formatted_today_date}-{path_name}-{crowd_pack_name}-{creative_name}"

    def generate_excel(self):
        """生成Excel文件"""
        try:
            # 验证输入
            errors = self.validate_inputs()
            if errors:
                messagebox.showerror("输入错误", "\n".join(errors))
                return
            audience_packages, celue_left_text, celue_right_text, chuilei_left_text, chuilei_right_text, creative_name_text, indus_qualify_text, keyword_behavior_text, keyword_content, keyword_interest_text, monitor_text, shopping_left_text, shopping_right_text, time_range, yuedu_left_text, yuedu_right_text = self.method_name_name()

            batch_data = {'账号名称': [], '账号ID': [], '计划名': [], '路径名称': [], '指定预算': [], '消耗速率': [], '单元名称': [], '笔记ID': [], '人群定向包': [], '性别': [], '地域': [], '年龄': [], '平台': [], '手机价格': [], '创意名称': [], '监测链接': [], '行业资质': []}

            if self.plan_num_text.get():
                try:
                    plan_num = int(self.plan_num_text.get())
                    for _ in range(plan_num):
                        batch_data['账号名称'].append(self.account_name.get())
                        batch_data['账号ID'].append(self.account_id.get())
                        batch_data['计划名'].append(self.generate_plan_name())
                        batch_data['路径名称'].append(self.path_name.get())
                        batch_data['指定预算'].append(float(self.plan_budget.get()))
                        batch_data['消耗速率'].append(self.consume_rate_text.get().strip())
                        batch_data['单元名称'].append(self.generate_plan_name())
                        batch_data['笔记ID'].append(self.unit_id.get())
                        batch_data['人群定向包'].append(self.map_target_type())
                        batch_data['性别'].append(self.gender.get())
                        batch_data['地域'].append(self.area.get())
                        batch_data['年龄'].append(self.get_selected_ages())
                        batch_data['平台'].append(self.platform.get())
                        batch_data['手机价格'].append(self.get_selected_tel_prices())
                        batch_data['创意名称'].append(creative_name_text)
                        batch_data['监测链接'].append(monitor_text)
                        batch_data['行业资质'].append(indus_qualify_text)
                except Exception as e:  # 转换失败捕获异常
                    self.lable_plan_num.config(foreground='red')
                    messagebox.showerror("输入错误", "生成计划条数必须是数字！")
                    return
            else:
                self.lable_plan_num.config(foreground='red')
                messagebox.showwarning("提示", "请输入要生成的数量！")
                return

            # 计划列表
            df = pd.DataFrame(batch_data)

            # 平台精选
            pingtaijingxuan_data = self.pingtaijingxuan_sheet_fill()

            # 行业人群
            hangyerenqun_data = self.hangyerenqun_sheet_fill(celue_left_text, celue_right_text, chuilei_left_text, chuilei_right_text)

            # 行业兴趣
            hangyexingqu_data = self.hangyexingqu_sheet_fill(yuedu_left_text, yuedu_right_text, shopping_left_text, shopping_right_text)

            # 关键词
            guanjianci_data = self.guanjianci_sheet_fill(keyword_interest_text, time_range, keyword_content, keyword_behavior_text)

            # 人群包
            renqunbao_data = self.renqunbao_sheet_fill(audience_packages)

            # 搜索组件
            sousuozujian_data = self.sousuozujian_sheet_fill()

            # 保存文件对话框
            # file_path = filedialog.asksaveasfilename(
            #     defaultextension=".xlsx",
            #     filetypes=[("Excel文件", "*.xlsx"), ("所有文件", "*.*")],
            #     initialfile="信息流-创建计划111.xlsx"
            # )

            file_path = "信息流-创建计划111.xlsx"
            # 生成excel文件
            if file_path:
                try:
                    # 1. 读取现有 Excel 文件（如果存在）
                    df_existing = pd.read_excel(file_path, sheet_name='计划列表')
                    # 2. 合并新旧数据（直接追加行）
                    df_combined = pd.concat([df_existing, df], ignore_index=True)
                    # 3. 重新写入文件（覆盖模式）
                    df_combined.to_excel(file_path, sheet_name='计划列表', index=False)
                    messagebox.showinfo("成功", f"数据已追加到 Excel 文件:\n{file_path}")
                except FileNotFoundError:
                    with pd.ExcelWriter(file_path, engine='openpyxl', mode='w') as writer:
                        df.to_excel(writer, sheet_name='计划列表', index=False)

                        # 写入平台精选
                        if pingtaijingxuan_data is not None:
                            df_pingtaijingxuan_sheet = pd.DataFrame(pingtaijingxuan_data)
                            df_pingtaijingxuan_sheet.to_excel(writer, sheet_name='平台精选', index=False)

                        # 写入行业人群
                        if hangyerenqun_data is not None:
                            df_hangyerenqun_data_sheet = pd.DataFrame(hangyerenqun_data)
                            df_hangyerenqun_data_sheet.to_excel(writer, sheet_name='行业人群', index=False)

                        # 写入行业兴趣
                        if hangyexingqu_data is not None:
                            df_hangyexingqu_data_sheet = pd.DataFrame(hangyexingqu_data)
                            df_hangyexingqu_data_sheet.to_excel(writer, sheet_name='行业兴趣', index=False)

                        # 写入关键词
                        if guanjianci_data is not None:
                            df_guanjianci_data_sheet = pd.DataFrame(guanjianci_data)
                            df_guanjianci_data_sheet.to_excel(writer, sheet_name='关键词', index=False)

                        # 写入人群包
                        if renqunbao_data is not None:
                            df_renqunbao_data_sheet = pd.DataFrame(renqunbao_data)
                            df_renqunbao_data_sheet.to_excel(writer, sheet_name='人群包', index=False)

                        # 写入搜索组件
                        if sousuozujian_data is not None:
                            df_sousuozujian_data_sheet = pd.DataFrame(sousuozujian_data)
                            df_sousuozujian_data_sheet.to_excel(writer, sheet_name='搜索组件', index=False)

                    messagebox.showinfo("成功", f"Excel文件已生成:\n{file_path}")
        except PermissionError:
            messagebox.showerror("错误", f"写入时需要关闭文件")
            return
        except Exception as e:
            logger.error(e)
            messagebox.showerror("错误", f"生成Excel时出错:\n{str(e)}")
            return

    def method_name_name(self):
        # 行业人群-策略人群-一级行业文本框
        celue_left_text = self.celue_left_text.get("1.0", tk.END).strip()
        # 行业人群-策略人群-人群包文本框
        celue_right_text = self.celue_right_text.get("1.0", tk.END).strip()
        # 行业人群-垂类人群-一级行业文本框
        chuilei_left_text = self.chuilei_left_text.get("1.0", tk.END).strip()
        # 行业人群-垂类人群-人群包文本框
        chuilei_right_text = self.chuilei_right_text.get("1.0", tk.END).strip()
        # 行业兴趣-行业阅读兴趣-一级兴趣
        yuedu_left_text = self.yuedu_left_text.get("1.0", tk.END).strip()
        # 行业兴趣-行业阅读兴趣-二级兴趣
        yuedu_right_text = self.yuedu_right_text.get("1.0", tk.END).strip()
        # 行业兴趣-行业购物兴趣-一级兴趣
        shopping_left_text = self.shopping_left_text.get("1.0", tk.END).strip()
        # 行业兴趣-行业购物兴趣-二级兴趣
        shopping_right_text = self.shopping_right_text.get("1.0", tk.END).strip()
        # 关键词兴趣文本框
        keyword_interest_text = self.keyword_interest_text.get("1.0", tk.END).strip()
        # 关键词行为时间范围、搜索内容、文本框
        time_range = self.time_range_var.get()  # 获取选中的时间范围值
        keyword_content = [option for option, var in self.keyword_content_vars.items() if var.get() == 1]
        keyword_behavior_text = self.keyword_behavior_text.get("1.0", tk.END).strip()
        # 人群包搜索文本框
        audience_packages = self.audience_package_text.get("1.0", tk.END).strip()
        # 创意名称文本框
        creative_name_text = self.creative_name_text.get().strip()
        # 监测链接文本框
        monitor_text = self.monitor_text.get("1.0", tk.END).strip()
        # 行业资质文本框
        indus_qualify_text = self.indus_qualify_text.get().strip()
        return audience_packages, celue_left_text, celue_right_text, chuilei_left_text, chuilei_right_text, creative_name_text, indus_qualify_text, keyword_behavior_text, keyword_content, keyword_interest_text, monitor_text, shopping_left_text, shopping_right_text, time_range, yuedu_left_text, yuedu_right_text

    def pingtaijingxuan_sheet_fill(self):
        """动态生成平台精选表格数据"""
        selected_scenes = self.get_selected_scenes()
        selected_festivals = self.get_selected_festivals()

        # 使用列表推导式构建数据
        data = {
            '人群定向包': [],
            '小类': [],
            '一级选项': []
        }
        map_target_type = self.map_target_type()
        # 添加场景数据（如果存在）
        if selected_scenes:
            if self.split_pingtaijingxuan_var.get() == 1:
                print(f"我选了平台场景拆包, 我在场景人群开始拆包")
                for opt in selected_scenes:
                    data['人群定向包'].append(f"{map_target_type}-{opt}")
                    data['小类'].append('场景人群')
                    data['一级选项'].append(opt)
            else:
                data['人群定向包'].append(map_target_type)
                data['小类'].append('场景人群')
                data['一级选项'].append("\n".join(selected_scenes))

        # 添加节促数据（如果存在）
        if selected_festivals:
            print(f"我选了平台场景-拆包, 我在节促人群开始拆包")
            if self.split_pingtaijingxuan_var.get() == 1:
                for opt in selected_festivals:
                    data['人群定向包'].append(f"{map_target_type}-{opt}")
                    data['小类'].append('节促人群')
                    data['一级选项'].append(opt)
            else:
                data['人群定向包'].append(map_target_type)
                data['小类'].append('节促人群')
                data['一级选项'].append("\n".join(selected_festivals))

        if not data['人群定向包']:  # 如果所有列表都为空
            return None  # 或 raise ValueError("无有效数据")
        return data

    def hangyerenqun_sheet_fill(self, celue_left_text, celue_right_text, chuilei_left_text, chuilei_right_text):
        data = {
            '人群定向包': [],
            '小类': [],
            '一级选项': [],
            '二级选项': []
        }

        map_target_type = self.map_target_type()

        if celue_left_text:
            if self.split_hangyerenqun_var.get() == 1:
                if celue_right_text:
                    for opt in celue_right_text.split("\n\n"):
                        data['人群定向包'].append(f"{map_target_type}-{opt}")
                        data['小类'].append('策略人群')
                        data['一级选项'].append(celue_left_text)
                        data['二级选项'].append(opt)
            else:
                data['人群定向包'].append(self.map_target_type())
                data['小类'].append('策略人群')
                data['一级选项'].append(celue_left_text)
                if celue_right_text:
                    data['二级选项'].append(celue_right_text)

        if chuilei_left_text:
            if self.split_hangyerenqun_var.get() == 1:
                if chuilei_right_text:
                    for opt in chuilei_right_text.split("\n\n"):
                        data['人群定向包'].append(f"{map_target_type}-{opt}")
                        data['小类'].append('策略人群')
                        data['一级选项'].append(chuilei_left_text)
                        data['二级选项'].append(opt)
            else:
                data['人群定向包'].append(map_target_type)
                data['小类'].append('垂类人群')
                data['一级选项'].append(chuilei_left_text)
                if chuilei_right_text:
                    data['二级选项'].append(chuilei_right_text)

        if not data['人群定向包']:  # 如果所有列表都为空
            return None  # 或 raise ValueError("无有效数据")
        return data

    def hangyexingqu_sheet_fill(self, yuedu_left_text, yuedu_right_text, shopping_left_text, shopping_right_text):
        data = {
            '人群定向包': [],
            '小类': [],
            '一级选项': [],
            '二级选项': []
        }

        if yuedu_left_text:
            if self.split_hangyexingqu_var.get() == 1:
                for opt in yuedu_left_text.split("\n\n"):
                    data['人群定向包'].append(f"{self.map_target_type()}-{opt}")
                    data['小类'].append('行业阅读兴趣')
                    data['一级选项'].append(opt)
                    data['二级选项'].append(None)
            else:
                data['人群定向包'].append(self.map_target_type())
                data['小类'].append('行业阅读兴趣')
                data['一级选项'].append(yuedu_left_text)
                data['二级选项'].append(None)

        if shopping_left_text:
            if self.split_hangyexingqu_var.get() == 1:
                if shopping_right_text:
                    for opt in shopping_right_text.split("\n\n"):
                        data['人群定向包'].append(f"{self.map_target_type()}-{opt}")
                        data['小类'].append('行业购物兴趣')
                        data['一级选项'].append(shopping_left_text)
                        data['二级选项'].append(opt)
            else:
                data['人群定向包'].append(self.map_target_type())
                data['小类'].append('行业购物兴趣')
                data['一级选项'].append(shopping_left_text)
                if shopping_right_text:
                    data['二级选项'].append(shopping_right_text)

        if not data['人群定向包']:  # 如果所有列表都为空
            return None  # 或 raise ValueError("无有效数据")
        return data

    def guanjianci_sheet_fill(self, keyword_interest_text, time_range, keyword_content, keyword_behavior_text):
        data = {
            '人群定向包': [],
            '小类': [],
            '关键词': []
        }

        if keyword_interest_text:
            if self.split_guanjianci_var.get() == 1:
                for opt in keyword_interest_text.split("\n\n"):
                    data['人群定向包'].append(f"{self.map_target_type()}-{opt}")
                    data['小类'].append('关键词兴趣')
                    data['关键词'].append(opt)
            else:
                data['人群定向包'].append(self.map_target_type())
                data['小类'].append('关键词兴趣')
                data['关键词'].append(keyword_interest_text)

        if keyword_behavior_text:
            if self.split_guanjianci_var.get() == 1:
                for opt in keyword_interest_text.split("\n\n"):
                    data['人群定向包'].append(f"{self.map_target_type()}-{opt}")
                    data['小类'].append(f'关键词行为:{time_range}天内-{";".join(keyword_content)}')
                    data['关键词'].append(opt)
            else:
                data['人群定向包'].append(self.map_target_type())
                data['小类'].append(f'关键词行为:{time_range}天内-{";".join(keyword_content)}')
                data['关键词'].append(keyword_behavior_text)

        if not data['人群定向包']:  # 如果所有列表都为空
            return None  # 或 raise ValueError("无有效数据")
        return data

    def renqunbao_sheet_fill(self, audience_packages):
        data = {
            '人群定向包': [],
            '包名': []
        }
        if audience_packages:
            if self.split_renqunbao_var.get() == 1:
                for opt in audience_packages.split("\n\n"):
                    data['人群定向包'].append(f"{self.map_target_type()}-{opt}")
                    data['包名'].append(opt)
            else:
                data['人群定向包'].append(self.map_target_type())
                data['包名'].append(audience_packages)

        if not data['人群定向包']:  # 如果所有列表都为空
            return None  # 或 raise ValueError("无有效数据")
        return data

    def sousuozujian_sheet_fill(self):
        data = {
            '创意名称': [],
            '组件位置': [],
            '置顶评论文案': [],
            '搜索词': []
        }

        creative_name = self.creative_name_text.get().strip()

        b_var = self.bottom_var.get()
        c_var = self.comment_var.get()
        b_entry = self.bottom_entry.get().strip()
        c_entry = self.comment_entry.get().strip()

        if b_var == 0 and c_var == 0:
            return None

        if b_var == 1 and c_var == 0:
            data['创意名称'].append(creative_name)
            data['组件位置'].append("图片或视频底部")
            data['搜索词'].append(b_entry)
            data['置顶评论文案'].append(None)

        if c_var == 1 and b_var == 0:
            data['创意名称'].append(creative_name)
            data['组件位置'].append("置顶评论")
            data['置顶评论文案'].append(c_entry)
            data['搜索词'].append(None)

        if c_var == 1 and b_var == 1:
            data['创意名称'].append(creative_name)
            data['组件位置'].append("图片或视频底部\n置顶评论")
            data['置顶评论文案'].append(c_entry)
            data['搜索词'].append(b_entry)
        return data
if __name__ == "__main__":
    root = tk.Tk()
    app = XiaohongshuAdTool(root)
    root.mainloop()